﻿using System;
using System.Reflection;
using AutoMapper;

namespace NMA.Infrastructure.NHibernate.Service.Handler
{
    using NMA.Infrastructure.NHibernate.Service.Event;
    using NMA.Infrastructure.EventAggregator;
    using NMA.Domain.Shared.Specification;
    using NMA.Infrastructure.NHibernate.Container;
    using NMA.Domain.Model.Repository;
    using NMA.Infrastructure.NHibernate.DomainObject;    
    using NMA.Infrastructure.Logging;    

    public class AuditHandler : IConsumer<AuditEvent>
    {
        private readonly IAuditRepository _auditRepository = null;
        private readonly ISpecification<AuditEvent> _catAuditSpec = null;
        private static readonly ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public AuditHandler() : this(
            IoC.GetInstance<IAuditRepository>(),
            IoC.GetInstance<ISpecification<AuditEvent>>()
            )
        { }

        public AuditHandler(IAuditRepository auditRepository, ISpecification<AuditEvent> catAuditSpec)
        {
            _auditRepository = auditRepository;
            _catAuditSpec = catAuditSpec;
        }

        public void Handle(AuditEvent catEvent)
        {
            try
            {
                if (_catAuditSpec.IsSatisfiedBy(catEvent))
                {
                    // auto mapper
                    var audit = Mapper.Map<AuditEvent, Audit>(catEvent);
                    audit.Id = Guid.NewGuid();

                    // adding the audit object to the database
                    var id = _auditRepository.Add(audit);
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
            }            
        }
    }
}